# 导入模块
import time
from selenium import webdriver
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


# TODO 创建Base类
class Base:
    # TODO 设置浏览器类型
    def __init__(self, browser):
        """
        判断使用的浏览器；
        打开浏览器;
        browser：浏览器
        窗口最大化
        """
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'ie':
            self.driver = webdriver.Ie()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('请使用以下浏览器:chrome|firefox|ie|edge')
            self.driver = None

        self.driver.maximize_window()

    # TODO 请求目标网址
    def get_website(self, url):
        """
        try:捕获异常
        url: 网址
        两种异常：selenium.common.exceptions.WebDriverException: Message: unknown
                selenium.common.exceptions.WebDriverException: Message: unknown
        """
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('网址不存在，重新输入网址')

    # TODO 定位元素
    def location_element(self, locator):
        """
        locator:元组
        try:捕获异常
        异常：NoSuchElementException
        """
        try:
            return WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(locator))
        except NoSuchElementException:
            print('未获取到元素')

    # TODO 元素点击操作
    def click(self, locator):
        """
        locator: 定位的元素
        try:捕获异常
        判定定位到的元素是否为空
        """
        # 调用location_element 方法获取定位元素
        element = self.location_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败')

    # TODO 获取元素属性
    def get_att(self, locator, values='outerHTML'):
        """
        locator: 定位元素
        attribute: 元素属性
        """
        # 获取定位元素
        attribute = self.location_element(locator)
        # 打印出源代码
        if attribute:
            return attribute.get_attribute(values) if attribute.get_attribute(values) else None
        else:
            print('未获取到元素')

    # TODO 后退
    def retreat(self):
        """
        back:浏览器后退
        """
        self.driver.back()

    # TODO 前进
    def forward(self):
        """
        forward:浏览器前进
        """
        self.driver.forward()

    # TODO 刷新
    def refresh(self):
        """
        refresh:浏览器刷新
        """
        self.driver.refresh()

    # TODO 退出浏览器
    def quit(self, seconds=0):
        """
        退出浏览器
        seconds:设置停顿秒数，默认0s
        """
        # 设置停顿秒数
        time.sleep(seconds)
        self.driver.quit()
